#include "hal_dip.h"
#include "hk32c030xx_gpio.h"
#include "hal_tty.h"

static void dip_switch_init() {
	GPIO_InitTypeDef dip_sw;
	RCC_AHBPeriphClockCmd(DIP1_SWITCH_RCU, ENABLE);
	RCC_AHBPeriphClockCmd(DIP2_SWITCH_RCU, ENABLE);

	dip_sw.GPIO_Pin = DIP1_SWITCH_PIN | DIP2_SWITCH_PIN;
	dip_sw.GPIO_Mode = GPIO_Mode_IN;
	dip_sw.GPIO_OType = GPIO_OType_PP;
	dip_sw.GPIO_Speed = GPIO_Speed_10MHz;
	dip_sw.GPIO_PuPd = GPIO_PuPd_UP;
	dip_sw.GPIO_Schmit = GPIO_Schmit_Disable;
	GPIO_Init(DIP1_SWITCH_BASE, &dip_sw);
	
	dip_sw.GPIO_Pin = DIP3_SWITCH_PIN | DIP4_SWITCH_PIN;
	GPIO_Init(DIP2_SWITCH_BASE, &dip_sw);
}

static uint8_t dip_switch_scan() {
	uint8_t dip_val = 0;
	
	uint16_t dip1_sw = GPIO_ReadInputData(DIP1_SWITCH_BASE);
	uint16_t dip2_sw = GPIO_ReadInputData(DIP2_SWITCH_BASE);

	if(!(dip1_sw & DIP1_SWITCH_PIN))
		dip_val |= 1 << 3;
	
	if(!(dip1_sw & DIP2_SWITCH_PIN))
		dip_val |= 1 << 2;
	
	if(!(dip2_sw & DIP3_SWITCH_PIN))
		dip_val |= 1 << 1;
	
	if(!(dip2_sw & DIP4_SWITCH_PIN))
		dip_val |= 1;
	
	return dip_val;
}

static uint8_t scan_dip_sw1() {
	if(GPIO_ReadInputDataBit(DIP1_SWITCH_BASE,DIP1_SWITCH_PIN))
		return 0;
	else 
		return 1;
}

static uint8_t scan_dip_sw2() {
	if(GPIO_ReadInputDataBit(DIP1_SWITCH_BASE,DIP2_SWITCH_PIN))
		return 0;
	else 
		return 1;
}

static uint8_t scan_dip_sw3() {
	if(GPIO_ReadInputDataBit(DIP2_SWITCH_BASE,DIP3_SWITCH_PIN))
		return 0;
	else 
		return 1;
}

static uint8_t scan_dip_sw4() {
	if(GPIO_ReadInputDataBit(DIP2_SWITCH_BASE,DIP4_SWITCH_PIN))
		return 0;
	else 
		return 1;
}

const dip_switch_t g_dip_ = {
    dip_switch_init,
    dip_switch_scan,
	scan_dip_sw1,
	scan_dip_sw2,
	scan_dip_sw3,
	scan_dip_sw4,	
};